import xml.etree.ElementTree as ET

import cv2
import numpy as np
import spectral.io.envi as envi
from matplotlib import pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from numpy import flip

for ii in range(1, 7):
    dark_ref = envi.open('pathology/data/032370b-20x-roi%s.hdr'%ii, 'pathology/data/032370b-20x-roi%s.raw'%ii)
    dark_nparr = np.array(dark_ref.load())
    dark_nparr = flip(dark_nparr, 0)
    tree = ET.parse('/home/liyuan/Programming/python/pathology/pathology/data/032370b-20x-roi%i.xml'%ii)
    polygon = tree.getroot().findall('object/polygon')
    mask = np.zeros((dark_nparr.shape[0], dark_nparr.shape[1]), dtype="uint8")
    for p in polygon:
        x = p.findall('pt/x')
        y = p.findall('pt/y')
        x_coor = list(map(lambda x:int(x.text), x))
        y_coor = list(map(lambda y:int(y.text), y))
        c = []
        for x, y in zip(x_coor, y_coor):
            c.append([x, y])
        cor_xy = np.array(c)
	# cor_xy = np.hstack(mas(x_coor, y_coor))
        cv2.polylines(mask, np.int32([cor_xy]), 1, 1)
        cv2.fillPoly(mask, np.int32([cor_xy]), 1)
    # IMAGE = np.flipud(dark_nparr)
    IMAGE = dark_nparr
    GND = mask
    img = np.zeros(GND.shape[:2]+(3,), dtype=int)
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            if GND[i][j] == 0:
                color = np.array([0, 255, 0])
            elif GND[i][j] == 1:
                color = np.array([255, 0, 0])
            img[i, j] = color

        
    with PdfPages('标签%s.pdf'%ii) as pdf:
        fig = plt.figure()
        plt.imshow(img)
        height, width, channels = img.shape
        fig.set_size_inches(width / 100.0, height / 100.0)
        plt.gca().xaxis.set_major_locator(plt.NullLocator())
        plt.gca().yaxis.set_major_locator(plt.NullLocator())
        plt.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0, wspace=0)
        plt.margins(0, 0)
        plt.axis('off')
        plt.xticks([])
        plt.yticks([])  
        pdf.savefig(bbox_inches = 'tight')  # saves the current figure into a pdf page
        plt.close()




    img = IMAGE[:,:,[30,15,10]]
    img = img/img.max()
    
    with PdfPages('%s.pdf'%ii) as pdf:
        fig = plt.figure()
        plt.imshow(img)
        height, width, channels = img.shape
        fig.set_size_inches(width / 100.0, height / 100.0)
        plt.gca().xaxis.set_major_locator(plt.NullLocator())
        plt.gca().yaxis.set_major_locator(plt.NullLocator())
        plt.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0, wspace=0)
        plt.margins(0, 0)
        plt.axis('off')
        plt.xticks([])
        plt.yticks([])  
        pdf.savefig(bbox_inches = 'tight')  # saves the current figure into a pdf page
        plt.close()
